<template>
  <div
    class="flex-1 overflow-hidden relative"
    ref="playerContent"
    @click="cancelSelect"
  >
    <div
      class="p-2 border-b dark:border-darker border-gray-300 flex justify-between items-center"
    >
      <span class="font-medium">播放器</span>
      <div class="resolution-selector">
        <span class="text-sm mr-2">分辨率:</span>
        <select
          v-model="store.currentResolution"
          @change="onResolutionChange"
          class="text-sm border rounded px-2 py-1 bg-white dark:bg-gray-800 dark:text-white"
        >
          <option value="PORTRAIT">720 × 1280 (竖屏)</option>
          <option value="LANDSCAPE">1280 × 720 (横屏)</option>
        </select>
      </div>
    </div>
    <Player :containerSize="containerSize" />
  </div>
</template>

<script setup lang="ts">
import Player from "@/components/item/player/Player.vue";
import { usePlayerState } from "@/stores/playerState";
import { usePageState } from "@/stores/pageState";
import { watch, ref, onMounted, reactive } from "vue";
import { useTrackState } from "@/stores/trackState";

const pageStore = usePageState();
const store = usePlayerState();
const trackStore = useTrackState();
const playerContent = ref();
const containerSize = reactive({
  width: 0,
  height: 0,
});

function cancelSelect(event: MouseEvent) {
  event.stopPropagation();
  trackStore.selectTrackItem.line = -1;
  trackStore.selectTrackItem.index = -1;
}

// 处理分辨率切换
function onResolutionChange() {
  store.changeResolution(store.currentResolution);
}
// 更新画布尺寸
function updateContainerSize() {
  if (!playerContent.value) return;
  // 获取播放器内容元素的宽度和高度 getBoundingClientRect()是DOM原生方法
  let { width, height } = playerContent.value.getBoundingClientRect();
  containerSize.width = width;
  containerSize.height = height;
}
onMounted(() => {
  updateContainerSize();
});

// 监听窗口大小变化，更新画布尺寸
window.addEventListener("resize", updateContainerSize);

watch(
  () => pageStore.trackHeight,
  () => {
    updateContainerSize();
  },
  {
    // flush: 'post' 表示将 watch 监听器的回调函数延迟到组件渲染周期的后阶段执行
    flush: "post",
  }
);
watch(
  [() => store.playerHeight, () => store.playerWidth],
  () => {
    updateContainerSize();
  },
  {
    flush: "post",
  }
);
</script>
